// app.js
App({
  globalData: {
    navHeight: 0,
    navTop: 0,
    statusBarHeight: 0,
    isLoggedIn: false,
    userInfo: null
  },

  onLaunch: function () {
    console.log('=== App onLaunch ===');
    
    // 初始化导航栏
    this.initNavBar();
    
    // 初始化登录状态
    this.initLoginStatus();
    
    // 设置导航拦截
    this.setupNavigationInterceptor();
  },

  onShow: function() {
    console.log('=== App onShow - 刷新登录状态 ===');
    this.refreshLoginStatus();
  },

  // 初始化导航栏
  initNavBar: function() {
    try {
      const menuButtonObject = wx.getMenuButtonBoundingClientRect();
      wx.getSystemInfo({
        success: res => {
          const statusBarHeight = res.statusBarHeight;
          const navTop = menuButtonObject.top;
          const navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2;
          
          this.globalData.navHeight = navHeight;
          this.globalData.navTop = navTop;
          this.globalData.statusBarHeight = statusBarHeight;
          
          console.log('导航栏初始化完成');
        },
        fail: (err) => {
          console.error('导航栏初始化失败:', err);
        }
      });
    } catch (error) {
      console.error('导航栏初始化异常:', error);
    }
  },

  // 初始化登录状态
  initLoginStatus: function() {
    const token = wx.getStorageSync('token');
    const userInfo = wx.getStorageSync('userInfo');
    
    this.globalData.isLoggedIn = !!token;
    this.globalData.userInfo = userInfo || null;
    
    console.log('初始化登录状态:', {
      isLoggedIn: this.globalData.isLoggedIn,
      hasToken: !!token,
      hasUserInfo: !!userInfo
    });
  },

  // 刷新登录状态
  refreshLoginStatus: function() {
    const oldStatus = this.globalData.isLoggedIn;
    const token = wx.getStorageSync('token');
    this.globalData.isLoggedIn = !!token;
    
    console.log('刷新登录状态:', {
      旧状态: oldStatus,
      新状态: this.globalData.isLoggedIn,
      token: token ? '存在' : '不存在'
    });
    
    // 如果状态变化，通知所有页面
    if (oldStatus !== this.globalData.isLoggedIn) {
      this.notifyLoginStatusChange();
    }
  },

  // 通知登录状态变化
  notifyLoginStatusChange: function() {
    // 获取所有页面实例并通知状态变化
    const pages = getCurrentPages();
    pages.forEach(page => {
      if (page && page.onLoginStatusChange) {
        page.onLoginStatusChange(this.globalData.isLoggedIn);
      }
    });
  },

  // 设置导航拦截器
  setupNavigationInterceptor: function() {
    console.log('设置导航拦截器');
    
    const self = this;
    
    // 保存原始方法
    const originalMethods = {
      navigateTo: wx.navigateTo,
      redirectTo: wx.redirectTo,
      switchTab: wx.switchTab,
      reLaunch: wx.reLaunch,
      navigateBack: wx.navigateBack
    };

    // 重写 navigateTo
    wx.navigateTo = function(options) {
      console.log('🚀 navigateTo 拦截:', options.url);
      self._checkAndNavigate(options, originalMethods.navigateTo);
    };

    // 重写 redirectTo
    wx.redirectTo = function(options) {
      console.log('🔄 redirectTo 拦截:', options.url);
      self._checkAndNavigate(options, originalMethods.redirectTo);
    };

    // 重写 switchTab
    wx.switchTab = function(options) {
      console.log('📱 switchTab 拦截:', options.url);
      self._checkAndNavigate(options, originalMethods.switchTab);
    };

    // 重写 reLaunch
    wx.reLaunch = function(options) {
      console.log('🔄 reLaunch 拦截:', options.url);
      self._checkAndNavigate(options, originalMethods.reLaunch);
    };
  },

  // 检查并导航
  _checkAndNavigate: function(options, originalMethod) {
    // 先刷新状态，确保是最新的
    this.refreshLoginStatus();
    
    const needAuth = this.needLogin(options.url);
    const isLoggedIn = this.globalData.isLoggedIn;
    
    console.log('导航检查:', {
      url: options.url,
      needAuth: needAuth,
      isLoggedIn: isLoggedIn,
      通过: !needAuth || isLoggedIn
    });

    if (needAuth && !isLoggedIn) {
      console.log('❌ 未登录，跳转到登录页');
      this.goToLogin(options.url);
      return;
    }

    console.log('✅ 允许跳转');
    originalMethod(options);
  },

  // 判断是否需要登录
  needLogin: function(url) {
    if (!url) return false;
    
    // 清理URL，移除参数
    const cleanUrl = url.split('?')[0];
    
    // 登录页不需要登录
    if (cleanUrl.includes('/pages/login/index')) {
      return false;
    }
    
    // 公开页面列表
    const publicPages = [
      '/pages/index/index',
      '/pages/help-center/index'
      // 添加其他公开页面
    ];
    
    // 检查是否是公开页面
    const isPublic = publicPages.some(page => cleanUrl.includes(page));
    
    return !isPublic;
  },

  // 跳转到登录页
  goToLogin: function(targetUrl) {
    console.log('🔐 跳转到登录页，目标:', targetUrl);
    
    // 使用 redirectTo 而不是 navigateTo，避免返回时重复拦截
    wx.redirectTo({
      url: '/pages/login/index?target=' + encodeURIComponent(targetUrl || '/pages/index/index'),
      fail: (err) => {
        console.error('跳转登录页失败:', err);
        // 失败时使用 reLaunch
        wx.reLaunch({
          url: '/pages/profile/index'
        });
      }
    });
  },

  // 登录成功
  loginSuccess: function(userInfo, token) {
    console.log('🎉 登录成功开始');
    
    // 生成或使用提供的token
    const authToken = token || 'token_' + Date.now() + '_' + Math.random().toString(36).substr(2);
    
    // 保存到存储
    wx.setStorage({
      key: 'token',
      data: authToken,
      success: () => {
        console.log('Token 保存成功');
      }
    });
    
    wx.setStorage({
      key: 'userInfo',
      data: userInfo,
      success: () => {
        console.log('用户信息保存成功');
      }
    });

    // 立即更新全局状态
    this.globalData.isLoggedIn = true;
    this.globalData.userInfo = userInfo;
    
    console.log('✅ 全局状态已更新:', this.globalData);

    // 显示成功提示
    wx.showToast({
      title: '登录成功',
      icon: 'success',
      duration: 1500
    });

    // 延迟处理跳转，确保状态已更新
    setTimeout(() => {
      this.handleAfterLogin();
    }, 1000);
  },

  // 登录后处理
  handleAfterLogin: function() {
    const pages = getCurrentPages();
    console.log('当前页面栈:', pages.map(p => p.route));
    
    // 查找登录页
    const loginPageIndex = pages.findIndex(page => 
      page.route && page.route.includes('login')
    );
    
    if (loginPageIndex >= 0) {
      // 如果在登录页，返回上一页或跳转
      const delta = pages.length - loginPageIndex;
      console.log('从登录页返回，delta:', delta);
      
      if (delta > 1) {
        wx.navigateBack({
          delta: delta - 1
        });
      } else {
        wx.switchTab({
          url: '/pages/index/index'
        });
      }
    } else {
      // 不在登录页，刷新当前页
      const currentPage = pages[pages.length - 1];
      if (currentPage && currentPage.onShow) {
        currentPage.onShow();
      }
    }
  },

  // 退出登录
  logout: function() {
    console.log('🚪 退出登录开始');
    
    // 清除存储
    wx.removeStorageSync('token');
    wx.removeStorageSync('userInfo');
    
    // 更新全局状态
    this.globalData.isLoggedIn = false;
    this.globalData.userInfo = null;
    
    console.log('✅ 退出登录完成，全局状态:', this.globalData);
    
    // 跳转到首页
    wx.reLaunch({
      url: '/pages/index/index'
    });
  },

  // 检查认证状态
  checkAuth: function() {
    this.refreshLoginStatus();
    if (!this.globalData.isLoggedIn) {
      this.goToLogin();
      return false;
    }
    return true;
  }
});
